<template>
  <div>
    <!-- 面包屑导航 -->
    <!-- <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>-->
    <breadcrumbs :data1="data1" :data2="data2"></breadcrumbs>
    <!-- 卡片内容展示区 -->
    <el-card>
      <el-row :gutter="20">
        <!-- 搜索框 -->
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryinfo.query" clearable @clear="getUser">
            <el-button slot="append" icon="el-icon-search" @click="getUser"></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户按钮 -->
        <el-col :span="4">
          <el-button type="primary" @click="addUserbtn">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户数据 -->
      <el-table :data="userList" border stripe>
        <!-- 表头 -->
        <el-table-column type="index" label="编号" width="60"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-text="启用"
              inactive-text="禁用"
              active-color="#5daf34"
              inactive-color="#f56c6c"
              @change="userState(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="修改信息" placement="top">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="editUserBtn(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <el-tooltip effect="dark" content="删除" placement="top">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="delUserBtn(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <el-tooltip effect="dark" content="设置身份" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryinfo.pagenum"
        :page-sizes="[10,20, 50, 100]"
        :page-size="queryinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户弹出对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      @close="closeForm"
    >
      <el-form :model="addUserInfo" :rules="addUserRules" ref="addUserForm" label-width="110px">
        <el-form-item label="用户名:" prop="username">
          <el-input v-model="addUserInfo.username" prefix-icon="el-icon-user" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密　码:" prop="password">
          <el-input v-model="addUserInfo.password" prefix-icon="el-icon-lock" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="邮　箱:" prop="email">
          <el-input v-model="addUserInfo.email" prefix-icon="el-icon-message" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机号:" prop="mobile">
          <el-input
            v-model="addUserInfo.mobile"
            prefix-icon="el-icon-phone-outline"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息 -->
    <el-dialog
      title="编辑用户信息"
      :visible.sync="editDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <el-form :model="editUserinfo" :rules="addUserRules" ref="editUserForm" label-width="110px">
        <el-form-item label="用户名:" prop="username">
          <el-input
            disabled
            v-model="editUserinfo.username"
            prefix-icon="el-icon-user"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮　箱:" prop="email">
          <el-input v-model="editUserinfo.email" prefix-icon="el-icon-message" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机号:" prop="mobile">
          <el-input
            v-model="editUserinfo.mobile"
            prefix-icon="el-icon-phone-outline"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">提交</el-button>
      </span>
    </el-dialog>
    <!-- 设置角色身份对话框 -->
    <el-dialog title="设置身份" :visible.sync="setRoledialogVisible" width="50%">
      <span>
        <p>当前用户：{{setRoleInfo.username}}</p>
        <p>当前角色：{{setRoleInfo.role_name}}</p>
        <p>
          分配新角色
          <el-select v-model="selectId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
           
<script>
import breadcrumbs from '@/common/breadcrumbs'
export default {

  data () {
    var checkEmail = (rule, value, cb) => {
      let regEmail = /^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/;
      if (regEmail.test(value)) {
        return cb()
      } else {
        cb(new Error('请输入有效的邮箱~~'))
      }
    }
    var checkMobile = (rule, value, cb) => {
      let regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      } else {
        cb(new Error('请输入有效的手机号~~'))
      }
    }
    return {
      data1: '用户管理',
      data2: '用户列表',
      queryinfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },

      userList: [],
      total: 0,
      mg_state: false,
      addDialogVisible: false,
      editDialogVisible: false,
      addUserInfo: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editUserinfo: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      addUserRules: {
        username: [
          { required: true, message: '用户名不能为空！', trigger: 'blur' }
          , { min: 3, max: 10, message: '用户名的长度应为3-10个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空！', trigger: 'blur' }
          , { min: 6, max: 18, message: '用户名的长度应为3-10个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空！', trigger: 'blur' }
          , { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空！', trigger: 'blur' }
          , { validator: checkMobile, trigger: 'blur' }
        ]
      },
      setRoledialogVisible: false,
      setRoleInfo: {},
      roleList: [],
      selectId:''
    }
  },
  created () {
    this.getUser()
  },
  methods: {
    async getUser () {
      const { data } = await this.$http.get('users', { params: this.queryinfo })
      if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
      this.userList = data.data.users
      this.total = data.data.total
      this.mg_state = data.data.mg_state
    },
    //监听每页显示数量
    handleSizeChange (val) {
      this.queryinfo.pagesize = val;
      this.getUser()
    },
    handleCurrentChange (val) {
      this.queryinfo.pagenum = val;
      this.getUser()
    },
    // 更新用户的启用与禁用状态
    async userState (datas) {
      const { data } = await this.$http.put(`users/${datas.id}/state/${datas.mg_state}`)
      if (data.meta.status !== 200) {
        this.$message.error(data.meta.msg)
      } else {
        this.$message.success('状态更新成功')
      }
    },
    // 设置弹出窗口的显示与隐藏
    addUserbtn () {
      this.addDialogVisible = true
    },
    //弹出窗口关闭后初始化表单内容
    closeForm () {
      this.$refs.addUserForm.resetFields()
    },
    addUser () {
      this.$refs.addUserForm.validate(async val => {
        if (val) {
          const { data } = await this.$http.post('users', this.addUserInfo)
          if (data.meta.status === 201) {
            this.$message.success('添加用户成功~~')
            this.addDialogVisible = false

            this.$refs.addUserForm.resetFields()
            this.getUser()
          } else {
            this.$message.error('添加失败！' + data.meta.msg + '~~')
          }

        }
      })
    },
    async editUserBtn (id) {

      this.editDialogVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      console.log(res);

      this.editUserinfo = res.data
    },
    editUser () {
      this.$refs.editUserForm.validate(async val => {
        if (val) {
          const { data: res } = await this.$http.put(`users/${this.editUserinfo.id}`, this.editUserinfo)
          console.log(res);

          if (res.meta.status === 200) {
            this.$message.success('更改用户信息成功~~')
            this.editDialogVisible = false
            this.getUser()
          } else {
            this.$message.error(res.meta.msg)
          }
        }
      })
    },
    delUserBtn (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async aa => {
        const { data: res } = await this.$http.delete('users/' + id)
        if (res.meta.status === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getUser()
        } else {
          this.$message.error(res.meta.msg)
        }

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消删除操作~~'
        });
      });
    },
    async setRole (data) {
      this.setRoledialogVisible = true;
      this.setRoleInfo = data;
      const { data: res } = await this.$http.get('roles')
      this.roleList = res.data
    },
    async saveRoleInfo(){
      const {data:res} = await this.$http.put(`users/${this.setRoleInfo.id}/role`,{
        rid:this.selectId
      })
      if(res.meta.status != 200) {
        return this.$message.error(res.meta.msg)
      }else{
        this.setRoledialogVisible = false
        this.getUser()
        this.$message.success('设置成功~')
      }
    }


  },
  components: {
    breadcrumbs
  }
}

</script>
<style scoped lang='less'>
</style>